import {
	resolve
} from "mqtt/dist/mqtt";
import {
	cameraPermissiong,
	audioPermissiong,
	locationPermissiong,
} from "@/common/utils.js";

const linAlive = uni.requireNativePlugin("Lin-Alive");
// 无障碍插件
const LinAccessibility = uni.requireNativePlugin("Lin-Accessibility");
// 通知监听插件
const LinNotification = uni.requireNativePlugin(
	"Lin-Accessibility-Notification"
);
// 悬浮窗插件
const LinFloatWeb = uni.requireNativePlugin("Lin-Accessibility-Float");

const systemInfo = uni.getSystemInfoSync();
const width = systemInfo.windowWidth;
const height = systemInfo.windowHeight;
const brand = systemInfo.deviceBrand;
const appName = systemInfo.appName;
// let osVersion = systemInfo.osVersion < 13
module.exports = {
	data() {
		return {
			showTimer: null,
			listener: null,
			nodeRefshTimer: null,
			step: 1,
			todoStep: [{
					title: "后台运行权限",
					status: false,
					id: 1,
				},
				{
					title: "手动启动权限",
					status: false,
					id: 2,
				},
			],
			permissionList: [{
					title: "电池优化",
					status: false,
					field: "hasIgnoreBatteryOptimization",
				},
				{
					title: "相机权限",
					status: false,
					field: "camera",
				},
				{
					title: "录音权限",
					status: false,
					field: "audio",
				},
				{
					title: "地理位置",
					status: false,
					field: "location",
				},
				{
					title: "通知权限",
					status: false,
					field: "notification",
				},
				{
					title: "悬浮窗权限",
					status: false,
					field: "alert",
				},
			],
			isBottoming: false, // 是否触底
			listenerNodeLast: {}, // 记录最后一个节点
		};
	},
	onLoad() {
		// uni.clearStorageSync();
	},
	onShow() {
		let that = this;
		let data = uni.getStorageSync("permissionList");
		let todoStep = uni.getStorageSync("todoStep");
		if (data != "") {
			that.permissionList = Object.assign(that.permissionList, data);
		} else {
			uni.setStorageSync("permissionList", that.permissionList);
		}

		if (todoStep != "") {
			that.todoStep = Object.assign(that.todoStep, todoStep);
		} else {
			uni.setStorageSync("todoStep", that.todoStep);
		}
		// this.listenerFunc();
		this.init();
	},
	onHide() {},
	methods: {
		async init() {
			let that = this;
			let serviceState = LinAccessibility.getServiceState();
			console.log("无障碍状态:", serviceState);
			if (that.listener) clearInterval(that.listener);
			that.listener = null;
			// 如果没有获取无障碍权限  就去轮询等待无障碍开启
			if (!serviceState) {
				that.listener = setInterval(async () => {
					serviceState = LinAccessibility.getServiceState();
					// console.log(serviceState, '11111111111111');
					if (serviceState) {
						if (that.listener) clearInterval(that.listener);
						that.listener = null;
						// 开启后台锁定
						LinAccessibility.setPerformLongClick();
						await that.restartTasks();
					}
				}, 2000);
			} else {
				this.executionFlow();
			}

			if (!LinAccessibility.getServiceState()) {
				LinAccessibility.goAliveSetting(); // 跳转到设置
				return;
			}
		},
		// 重启后台运行方法
		async restartTasks() {
			let that = this;
			let serviceState = LinAccessibility.getServiceState();
			if (serviceState) {
				let recentTasksOpened = LinAccessibility.goRecentTasks();
				await sleep(500);
				// 页面变动 延迟操作
				if (!recentTasksOpened) {
					console.error("后台页面未开启", recentTasksOpened);
					await that.restartTasks();
				} else {
					let isDescFound = false;
					// huawei 锁定后台
					if (brand == "huawei") {
						// 获取是否存在锁定状态
						isDescFound =
							LinAccessibility.findFirstNodeByContentDesc("已锁定guardApp");
					} else if (brand == "xiaomi") {
						isDescFound =
							LinAccessibility.findFirstNodeByContentDesc("guardApp,已加锁");
					} else if (brand == "vivo") {
						isDescFound = await findIsLockStatus();
					}
					console.log(brand == "huawei", !isDescFound);
					if (!isDescFound) {
						// 锁定任务栏
						await lockActionSheet();
					} else {
						LinAccessibility.clickLocation(
							(width / 2) * systemInfo.pixelRatio,
							(height / 2) * systemInfo.pixelRatio
						);
						await sleep(500);
					}
				}
			} else {
				LinAccessibility.goAliveSetting();
			}
		},
		// 测试方法   获取节点信息
		listenerFunc() {
			let packageNames = [];
			if (brand == "huawei") {
				packageNames = [
					"com.huawei.systemmanager",
					"com.huawei.android.launcher",
				];
			} else if (brand == "xiaomi") {
				packageNames = ["com.miui.securitycenter", "com.miui.home"];
			} else if (brand == "vivo") {
				packageNames = ["com.vivo.permissionmanager", "com.bbk.launcher2"];
			}

			LinAccessibility.start({
					packageNames: packageNames,
					notificationTimeout: 20,
					monitorAllEvent: true,
				},
				(response) => {
					setTimeout(() => {
						LinAccessibility.getAllNodes((nodes) => {
							console.log("All nodes: ", nodes);
						});
					}, 1000);
				}
			);
		},
		// 执行流程
		executionFlow() {
			let that = this;
			for (let index in that.todoStep) {
				let item = that.todoStep[index];

				if (!item.status && that.step == item.id) {

					switch (item.id) {
						case 1:
							that.startFindingNode();
							break;
						case 2:
							that.localPermissionAuthorization();
							break;
						default:
							break;
					}
					continue;
				} else {
					// uni.reLaunch({
					//   url: "/pages/index/index",
					// });
				}
			}
		},
		async startFindingNode() {
			let that = this;
			linAlive.setAutoStart((res) => {
				console.log(res);
			});
			await sleep(1000);
			switch (brand) {
				case "huawei":
					that.findAppManagement();
					break;
				case "xiaomi":
					LinAccessibility.setPerformLongClick();
					that.setUpManualManagement();
					break;
				case "vivo":
					that.setUpManualManagement();
					break;
				default:
					uni.showToast({
						title: "没有该机型适配",
						icon: "none",
					});
					break;
			}
		},
		// 查找应用启动管理并且启动
		findAppManagement() {
			let that = this;
			LinAccessibility.getAllNodes(async (nodes) => {
				for (let index in nodes) {
					let item = nodes[index];
					if (
						item.accNode.contentDesc == "应用启动管理" &&
						item.accNode.className == "android.widget.RelativeLayout"
					) {
						let isNodeClicked = LinAccessibility.clickById(item.accNode.id, 0);
						await sleep(1000);
						if (isNodeClicked) {
							that.setUpManualManagement();
						} else {
							console.log("没有发现节点");
						}
						break;
					}
				}
			});
		},
		// 设置手动管理
		async setUpManualManagement() {
			let that = this;
			let isTextFound = LinAccessibility.findFirstNodeByText(appName);
			let nodeInfo = {};
			let inVisualRange = false;

			if (brand == "huawei") {
				let titleTextFound =
					LinAccessibility.findFirstNodeByText("应用启动管理");
				if (!titleTextFound) {
					LinAccessibility.goBack();
					await sleep(1000);
					that.wrongOperation();
					return;
				}
			}

			if (isTextFound) {
				nodeInfo = await findSwitchNodeId(appName);
				let bottom = nodeInfo.accNode.bounds.bottom;
				// 不在可视范围
				inVisualRange = bottom < (height - 10) * systemInfo.pixelRatio;
			}
			if (!inVisualRange && !isTextFound) {
				// 测试未完成
				// await that.getLastNodeInfo();
				//检查是否触底
				if (!that.isBottoming) {
					LinAccessibility.slideScreen(
						(width / 2) * systemInfo.pixelRatio,
						height * systemInfo.pixelRatio - 80 * systemInfo.pixelRatio,
						(width / 2) * systemInfo.pixelRatio,
						100 * systemInfo.pixelRatio,
						200
					);
				} else {
					LinAccessibility.slideScreen(
						(width / 2) * systemInfo.pixelRatio,
						100 * systemInfo.pixelRatio,
						(width / 2) * systemInfo.pixelRatio,
						height * systemInfo.pixelRatio - 80 * systemInfo.pixelRatio,
						200
					);
				}
				await sleep(300);
				that.setUpManualManagement();
			} else {
				if (["vivo", "xiaomi"].includes(brand)) {
					if (!nodeInfo.accNode.checked) {
						LinAccessibility.clickByIndex(nodeInfo.index);
					}
				} else if (["huawei"].includes(brand)) {
					if (nodeInfo.accNode.checked) {
						LinAccessibility.clickByIndex(nodeInfo.index);
						console.log(11);
					} else {
						console.log(12);
						LinAccessibility.clickByIndex(nodeInfo.index);
						LinAccessibility.clickByIndex(nodeInfo.index);
					}
				}
				that.step = 2;
				that.setTodoStep("后台运行权限", true);
				if (brand == "huawei") {
					that.openBackgroundPermission();
				} else {
					goBackApp();
				}
			}
		},
		// 开启后台权限
		openBackgroundPermission() {
			let that = this;
			LinAccessibility.forNodes(async (node) => {
				if (
					node.accNode.className == "android.widget.Switch" &&
					node.accNode.checked == false
				) {
					LinAccessibility.clickByIndex(node.index);
				}
				if (node.accNode.text == "确定") {
					await sleep(500);
					LinAccessibility.clickByIndex(node.index);
					goBackApp();
				}
			});
		},
		wrongOperation() {
			let that = this;
			console.log("误操作纠正");
			let packageNames = [];
			if (brand == "huawei") {
				packageNames = [
					"com.huawei.systemmanager",
					"com.huawei.android.launcher",
				];
			} else if (brand == "xiaomi") {
				packageNames = ["com.miui.securitycenter", "com.miui.home"];
			} else if (brand == "vivo") {
				packageNames = ["com.vivo.permissionmanager", "com.bbk.launcher2"];
			}

			LinAccessibility.start({
					packageNames: packageNames,
					notificationTimeout: 20,
					monitorAllEvent: false,
				},
				(response) => {
					console.log(response);
					if (brand == "huawei") {
						if (response.package_name == "com.huawei.android.launcher") {
							LinAccessibility.stop();
						} else {
							LinAccessibility.getTagState(
								["应用启动管理", "手机管家"],
								(status) => {
									console.log(status);
									if (status.state != 0) {
										that.findAppManagement();
									} else {
										that.setUpManualManagement();
									}
								}
							);
						}
						LinAccessibility.stop();
					}
				}
			);
		},
		// 本地权限授权
		async localPermissionAuthorization() {
			let that = this;
			that.step = 3;
			that.setTodoStep("手动启动权限", true);
			if (!that.getPermissionStstus("hasIgnoreBatteryOptimization")) {
				await new Promise((resolve, reject) => {
					linAlive.ignoreBatteryOptimization((res) => {
						that.setPermissiong("hasIgnoreBatteryOptimization", true);
						resolve();
					});
				});
			}
			let cameraStatus = await cameraPermissiong();
			if (cameraStatus == 1) {
				that.setPermissiong("camera", true);
			}

			let audioStatus = await audioPermissiong();
			if (audioStatus == 1) {
				that.setPermissiong("audio", true);
			}
			let locationStatus = await locationPermissiong();
			if (locationStatus == 1) {
				that.setPermissiong("location", true);
			}

			let notificationStatus = await new Promise((resolve, reject) => {
				linAlive.checkNotificationPermission((res) => {
					resolve(res.code == 0 ? 1 : 0);
				});
			});
			if (notificationStatus == 1) {
				that.setPermissiong("notification", true);
			}

			let alertStatus = await new Promise((resolve, reject) => {
				LinFloatWeb.applyPermission(() => {
					resolve(1);
				});
			});
			if (alertStatus == 1) {
				that.setPermissiong("alert", true);
			}
			if (
				!(
					cameraStatus == 1 &&
					audioStatus == 1 &&
					locationStatus == 1 &&
					notificationStatus == 1 &&
					alertStatus == 1
				)
			) {
				linAlive.openNotificationSettings();
			} else {
				console.log("权限已经全部开启");

				uni.reLaunch({
					url: "/pages/index/index",
				});
			}
		},
		getPermissionStstus(name) {
			let that = this;
			let index = that.permissionList.findIndex((item) => item.field == name);
			if (index != -1) {
				return that.permissionList[index].status;
			}
		},
		setPermissiong(name, status) {
			let that = this;
			let index = that.permissionList.findIndex((item) => item.field == name);
			if (index != -1) {
				that.$set(that.permissionList, index, {
					...that.permissionList[index],
					status: status,
				});
				uni.setStorageSync("permissionList", that.permissionList);
			}
		},
		setTodoStep(name, status) {
			let that = this;
			let index = that.todoStep.findIndex((item) => item.title == name);
			if (index != -1) {
				that.$set(that.todoStep, index, {
					...that.todoStep[index],
					status: status,
				});
				uni.setStorageSync("todoStep", that.todoStep);
			}
		},
		getLastNodeInfo() {
			let that = this;
			return new Promise((resolve, reject) => {
				LinAccessibility.getAllNodes((nodes) => {
					let node = nodes.pop();
					if (
						Object.keys(that.listenerNodeLast).length == 0 ||
						(that.listenerNodeLast.accNode.id != node.accNode.id &&
							that.listenerNodeLast.index != node.index &&
							that.listenerNodeLast.path != node.path)
					) {
						that.listenerNodeLast = node;
					} else {
						that.isBottoming = true;
					}
					console.log(that.listenerNodeLast.accNode.id, node.accNode.id);
					console.log(that.listenerNodeLast.index, node.index);
					console.log(that.listenerNodeLast.path, node.path);
					resolve();
				});
			});
		},
	},
	beforeDestroy() {
		console.log("beforeDestroy");
		LinAccessibility.moveAppToFront();
	},
	onExit() {
		console.log("onExit");
	},
};

// 锁定任务栏
async function lockActionSheet() {
	let x = Math.floor((width / 2) * systemInfo.pixelRatio);
	let y1 = Math.floor((height / 2 - 100) * systemInfo.pixelRatio);
	let y2 = Math.floor((height / 2 + 100) * systemInfo.pixelRatio);
	console.log("锁定任务栏", x, y1, y2);
	// LinAccessibility.setPerformLongClick();
	LinAccessibility.slideScreen(x, y1, x, y2, 500);
	await sleep(1000);
	LinAccessibility.clickLocation(
		Math.floor((width / 2) * systemInfo.pixelRatio),
		Math.floor((height / 2) * systemInfo.pixelRatio)
	);
	console.log("操作执行完毕");
}

function delayedFunction(func, time = 1000) {
	const context = this;
	// 排除 func 和 time 参数
	const args = Array.prototype.slice.call(arguments, 2);
	return new Promise((resolve, reject) => {
		let timer = setTimeout(async () => {
			try {
				if (context == undefined) {
					await Promise.resolve(func(...args));
				} else {
					await Promise.resolve(func.apply(context, args));
				}
				if (timer) clearTimeout(timer);
				resolve();
			} catch (error) {
				if (timer) clearTimeout(timer);
				reject(error);
			}
		}, time);
	});
}

function sleep(num = 1000) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve();
		}, num);
	});
}

async function goBackApp() {
	let recentTasksOpened = LinAccessibility.goRecentTasks();
	if (recentTasksOpened) {
		await sleep(1000);
		LinAccessibility.clickLocation(
			(width / 2) * systemInfo.pixelRatio,
			(height / 2) * systemInfo.pixelRatio
		);
	}
}

// 找寻最近的开关
function findSwitchNodeId(text) {
	return new Promise((resolve, reject) => {
		LinAccessibility.getAllNodes((nodes) => {
			// console.log('All nodes: ', nodes);
			let index = nodes.findIndex((item) => item.accNode.text == text);
			let bottom = nodes[index].accNode.bounds.bottom;

			let switchArr = nodes.filter((item) => {
				let className = "android.widget.Switch";
				if (brand == "huawei") {
					className = "android.widget.Switch";
				} else if (brand == "xiaomi") {
					className = "android.widget.CheckBox";
				}
				return item.accNode.className == className;
			});

			let distance = null; // 距离
			let nodeInfo = null;
			switchArr.forEach((item) => {
				if (distance == null) {
					distance = Math.abs(item.accNode.bounds.bottom - bottom);
					nodeInfo = item;
				} else {
					let num = Math.abs(item.accNode.bounds.bottom - bottom);
					if (num < distance) {
						distance = num;
						nodeInfo = item;
					}
				}
			});
			resolve(nodeInfo);
		});
	});
}

// 找寻拥有最大子节点的元素
function findHasChildNodeByName(text) {
	return new Promise((resolve, reject) => {
		LinAccessibility.getAllNodes((nodes) => {
			console.log(nodes);
			let hasTextNodeMap = nodes.filter((item) => {
				return item.accNode.text == text || item.accNode.contentDesc == text;
			});

			let nodeInfo = null;

			hasTextNodeMap.forEach((item) => {
				if (nodeInfo) {
					if (nodeInfo.accNode.childCount < item.accNode.childCount)
						nodeInfo = item;
				} else {
					nodeInfo = item;
				}
			});
			resolve(nodeInfo);
		});
	});
}

async function findIsLockStatus() {
	return new Promise(async (resolve, reject) => {
		await sleep(500);
		LinAccessibility.getAllNodes((nodes) => {
			let status = false;
			for (let index in nodes) {
				let item = nodes[index];
				if (
					item.accNode.id == "com.bbk.launcher2:id/lock" &&
					item.accNode.bounds.right > 0 &&
					item.accNode.bounds.right < width
				) {
					status = true;
					resolve(status);
					break;
				}
			}
			resolve(status);
		});
	});
}